<?php

namespace App\Services\Goods;

use App\CodeResponse;
use App\Enums\RuleTitleEnums;
use App\Exceptions\BusinessException;
use App\Models\GoodsModel;
use App\Services\BaseServices;
use Illuminate\Support\Facades\DB;

class GoodsServices extends BaseServices
{
    /**
     * @param  int  $goodsId
     * @return \App\Models\BaseModel|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getGoodsById(int $goodsId)
    {
        return GoodsModel::query()->where('id', $goodsId)->first();
    }

    /**
     * @param  array  $ids
     * @return GoodsModel[]|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getGoodsInId(array $ids)
    {
        return GoodsModel::query()->whereIn('id', $ids)->get();
    }

    /**
     * SKU
     * @param  int  $goodsId
     * @return array|false
     */
    public function goodsSku(int $goodsId)
    {
        $goodsSku = GoodsSkuServices::getInstance()->getGoodsSkuByGoodsId($goodsId);
        if (is_null($goodsSku)) {
            return false;
        }
        $rule = RuleServices::getInstance()->getRuleList();
        if (is_null($rule)) {
            return false;
        }
        foreach ($goodsSku->toArray() as $goodsSkuValue) {
            $goodsRuleArr[] = explode(",", $goodsSkuValue["ruleId"]);
        }
        $skuArr = [];
        foreach ($goodsRuleArr as $goodsRuleArrKey => $goodsRuleArrValue) {
            foreach ($rule->toArray() as $ruleValue) {
                if (in_array($ruleValue['id'], $goodsRuleArrValue)) {
                    $skuArr[$goodsRuleArrKey][] = ['name' => $ruleValue['ruleName'], 'id' => $ruleValue['id']];
                    $skuArr[$goodsRuleArrKey]['specId'] = $ruleValue['specId'];
                }
            }
        }
        $sku = [];
        foreach (RuleTitleEnums::RULE_TITLE as $titleValue) {
            foreach ($skuArr as $value) {
                if ($titleValue['id'] == $value['specId']) {
                    unset($value['specId']);
                    $sku[$titleValue['name']] = $value;
                }
            }
        }
        return $sku;
    }

    /**
     * 商品详情
     * @param  int  $goodsId
     * @return array|false
     */
    public function goodsDetails(int $goodsId)
    {
        $goods = $this->getGoodsById($goodsId);
        if (is_null($goods)) {
            return false;
        }
        $sku = $this->goodsSku($goodsId);
        return [
            'details' => $goods->toArray(),
            'sku' => $sku,
        ];
    }

    /**
     * @param  $time
     * @param  $type
     * @return array|false
     */
    public function goodsM($time, $type = "m")
    {
        $Ytime = $this->getDate($time, "y");
        $data = GoodsModel::query()->whereBetween("add_time",
            [$Ytime[1]['m_time_start'], $Ytime[1]['m_time_end']])->get();
        if (is_null($data)) {
            return false;
        }
        $result = [];
        if ($type == "y") {
            $Mtime = $Ytime;
        } else {
            $Mtime = $this->getDate($time, $type);
        }
        for ($i = 1; $i <= count($Mtime); $i++) {
            foreach ($data->toArray() as $value) {
                if ($value['addTime'] >= $Mtime[$i]['m_time_start'] && $value['addTime'] <= $Mtime[$i]['m_time_end']) {
                    $result[$i]['priceAll'][] = $value['price'];
                }
            }
        }
        $arr = [];
        foreach ($result as $key => $value) {
            $arr[$key]['allPrice'] = 0;
            for ($i = 0; $i < count($value["priceAll"]); $i++) {
                $arr[$key]['allPrice'] += $value['priceAll'][$i];
            }
        }
        return $arr;
    }

    /**
     * 获取时间
     * @param  int  $time
     * @param  string  $type
     * @param  int  $m
     * @param  int  $d
     * @return array
     */
    public function getDate($time = 2021, $type = "m", $m = 1, $d = 1)
    {

        $Mtime = [];
        if ($type == "m") {
            for ($i = 1; $i < 13; $i++) {
                $Mtime[$i]['m_time_start'] = strtotime($time."-".$i);//指定月份月初时间戳
                $Mtime[$i]['m_time_end'] = mktime(23, 59, 59, date('m', strtotime($time."-".$i)) + 1, 00);//指定月份月末时间戳
            }
        } elseif ($type == "y") {
            $Mtime[1]['m_time_start'] = strtotime($time."-1");//指定月份月初时间戳
            $Mtime[1]['m_time_end'] = mktime(23, 59, 59, date('m', strtotime($time."-12")) + 1, 00);//指定月份月末时间戳
        } elseif ($type == "d") {
            $Mtime[1]['m_time_start'] = strtotime("$time-$m-$d 00:00:00");
            $Mtime[1]['m_time_start'] = (int) bcsub($Mtime[1]['m_time_start'], 28800);
            $Mtime[1]['m_time_end'] = (int) bcadd($Mtime[1]['m_time_start'], 86399);
        }
        return $Mtime;
    }

    /**
     * gm 游戏数据明细
     */
    public function gameDetail($year, $month, $time, $game_id, $size, $page)
    {
        $field = $this->field("FROM_UNIXTIME(pay_time,'%Y-%m-%d') pay_time,user_id,game_id,game_name,pay_amount,pay_way,pay_game_amount");
        if (!empty($year) && empty($month) && empty($time)) {
            $year_start = date('Y', strtotime("$year"));
            $year_end = date('Y', strtotime("$year+2 year"));
            $field->where('pay_time', '>=', strtotime($year_start.'-01-01'))
                ->where('pay_time', '<', strtotime($year_end.'-01-01'));//年份查询
        }
        if (!empty($year) && !empty($month) && empty($time)) {
            $month_start = date('Y-m', strtotime("$month -1 month"));
            $month_end = date('Y-m', strtotime("$month +1 month"));
            $field->where('pay_time', '>=', strtotime("$month_start +1 month"))
                ->where('pay_time', '<', strtotime("$month_end +1 month - 1day"));//月份查询
        }
        if (!empty($year) && !empty($month) && !empty($time)) {
            $time_start = strtotime($time);
            $field->where('pay_time', '>=', $time_start)->where('pay_time', '<', $time_start + 86400);//天查询
        }
        $ret = $field->where('pay_status', 1)
            ->where('game_id', $game_id)
            ->order('pay_time desc')
            ->paginate($size, false, ['page' => $page])->toArray();

        foreach ($ret['data'] as &$data) {
            if ($data['pay_way'] == 2 || $data['pay_way'] == 4 || $data['pay_way'] == 6) {
                $data['charges'] = round($data['pay_game_amount'] * 0.02, 2);
            } else {
                $data['charges'] = round($data['pay_game_amount'] * 0.01, 2);
            }
        }

        return $ret;

    }


    public function goodsDay()
    {
    }
}
